﻿using AutoMapper;
using PowerHub.MES.Common.NumberingCenter;
using PowerHub.MES.DTO.Shopfloor.DTO;
using PowerHub.MES.DTO.Shopfloor.QueryDTO;
using PowerHub.MES.EFBase;
using PowerHub.MES.Entities.Shopfloor;
using PowerHub.MES.Entities;
using PowerHub.MES.IRepository.IShopfloor;
using PowerHub.MES.IServices.IShopfloor;
using PowerHub.MES.Jwt;
using PowerHub.MES.ReturnEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PowerHub.MES.Entities.Crew;
using PowerHub.MES.DTO.Crew.QueryDto;
using PowerHub.MES.DTO.Crew.DTO;
using PowerHub.MES.IServices.ICrew;
using PowerHub.MES.IRepository.ICrew;
using PowerHub.MES.Entities.BasicData;

namespace PowerHub.MES.Services.Crew
{
    /// <summary>
    /// 班组设置接口实现层
    /// </summary>
    public class Crew_TeamBillServices : BaseServices<Crew_TeamBill>, ICrew_TeamBillServices
    {
        private ICrew_TeamBillRepository _iCrew_TeamBillRepository;
        private ICrew_TeamBillDetialRepository _crew_TeamBillDetialRepository;
        public UserServices _userServices;
        private IMapper _mapper;
        private static Random random = new Random();

        public Crew_TeamBillServices(PowerHubMesContext powerHubMesContext, ICrew_TeamBillRepository iCrew_TeamBillRepository,
            UserServices userServices, IMapper mapper, ICrew_TeamBillDetialRepository crew_TeamBillDetialRepository) : base(powerHubMesContext)
        {
            _iCrew_TeamBillRepository = iCrew_TeamBillRepository;
            _userServices = userServices;
            _mapper = mapper;
            _crew_TeamBillDetialRepository = crew_TeamBillDetialRepository;
        }

        /// <summary>
        /// 获取班组设置列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationPageResult<List<Crew_TeamBill>>> GetCrew_TeamBillPageListAsync(QueryCrew_TeamBillDTO query)
        {
            var ss = _userServices.UserId;
            var UserName = _userServices.UserName;
            var Role = _userServices.Role;
            return await _iCrew_TeamBillRepository.GetCrew_TeamBillPageListAsync(query);
        }

        /// <summary>
        /// 添加班组设置
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> CreateCrew_TeamBillAsync(Crew_TeamBillDTO query)
        {
            Crew_TeamBill foundation = await GetEntityAsync(d => d.TeamName.Equals(query.TeamName) && d.IsDel == 0);
            if (foundation != null)
            {
                throw new Exception("你输入的班组设置名称已存在！");
            }
            //实体转换
            var Crew_TeamBill = _mapper.Map<Crew_TeamBill>(query);
            Crew_TeamBill.Id = Guid.NewGuid().ToString();
            Crew_TeamBill.TeamNo = string.IsNullOrEmpty(query.TeamNo) || query.TeamNo.Contains(" ") ? GenerateBasicDataNO.GenerateCode(query.TeamName) : query.TeamNo;
            Crew_TeamBill.Creator = _userServices.UserName;

            //添加明细
            foreach (var item in query.userIds)
            {
                Crew_TeamBill.CrewTeamBillDetials.Add(new Crew_TeamBillDetial { Id = Guid.NewGuid().ToString(), TeamId = Crew_TeamBill.Id, UserId = item });
            }



            return await _iCrew_TeamBillRepository.CreateCrew_TeamBillAsync(Crew_TeamBill);
        }


        /// <summary>
        /// 批量删除班组设置
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> DeletionCrew_TeamBillAsync(List<string>? ids)
        {
            if (ids.Count < 1)
            {
                throw new Exception("请先选择数据！");
            }
            return await _iCrew_TeamBillRepository.DeletionCrew_TeamBillAsync(ids);
        }


        /// <summary>
        /// 更新班组设置
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> UpdateCrew_TeamBillAsync(Crew_TeamBillDTO query)
        {
            if (query == null)
            {
                throw new Exception("请先选择数据！");
            }

            var TeamBill = await _iCrew_TeamBillRepository.GetCrew_TeamBillAsync(query.Id);

            //根据id获取班组设置信息
            if (TeamBill == null)
            {
                throw new Exception("更新班组设置信息发生了异常,请刷新页面后试试");
            }
            TeamBill.TeamName = query.TeamName;
            TeamBill.TeamTypeId = query.TeamTypeId;
            TeamBill.UserId = query.UserId;
            TeamBill.Updator = _userServices.UserName;


            //取出用户id
            var TeamBillDetiaUserIds = TeamBill.CrewTeamBillDetials.Select(c => c.UserId);

            //取传来与已存差集（新增）
            var adduserId = query.userIds.Except(TeamBillDetiaUserIds).ToList();
            List<Crew_TeamBillDetial> createRoleinfo_MenuInfos = adduserId
            .Select(user => new Crew_TeamBillDetial
            {
                Id = Guid.NewGuid().ToString(),
                UserId = user,
                TeamId = TeamBill.Id,
                Creator = _userServices.UserName,
            })
            .ToList();


            //取已存与传来差集（删除）
            var deleteuserIds = TeamBillDetiaUserIds.Except(query.userIds).ToList();
            var deleteTeamBillDetia = TeamBill.CrewTeamBillDetials.Where(c => deleteuserIds.Contains(c.UserId)).ToList();

            TeamBill.CrewTeamBillDetials = null;
            return await _iCrew_TeamBillRepository.UpdateCrew_TeamBillAsync(createRoleinfo_MenuInfos, deleteTeamBillDetia,TeamBill);
        }


        /// <summary>
        /// 获取明细
        /// </summary>
        /// <param name="pageQuery"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationPageResult<List<BasicData_Userinfo>>> GetCrew_TeamBillDetialPageListAsync(QueryCrew_TeamBillDetialDTO pageQuery)
        {
            return await _crew_TeamBillDetialRepository.GetCrew_TeamBillDetialPageListAsync(pageQuery);
        }
    }
}
